<?php
declare(strict_types=1);

namespace think\admin\test\service;

use think\admin\Service;
use think\admin\test\repository\OrderRepository;
use think\admin\test\repository\UserRepository;
use think\admin\test\repository\ProductRepository;
use think\admin\exception\BusinessException;

class OrderService extends Service
{
    /**
     * 仓储类型定义
     */
    public const REPOSITORY_USER = 'user';
    public const REPOSITORY_PRODUCT = 'product';

    /**
     * 服务类型定义
     */
    public const SERVICE_PAYMENT = 'payment';

    /**
     * 初始化
     * @throws BusinessException
     */
    protected function initialize(): void
    {
        // 设置订单主仓储 - 用于订单的基础操作
        $this->repository = new OrderRepository($this->app);
        
        // 注册用户仓储 - 用于用户信息和余额管理
        $this->registerRepository(self::REPOSITORY_USER, new UserRepository($this->app));
        
        // 注册商品仓储 - 用于商品信息和库存管理
        $this->registerRepository(self::REPOSITORY_PRODUCT, new ProductRepository($this->app));

        // 注册支付服务 - 用于处理支付相关业务
        $this->registerService(self::SERVICE_PAYMENT, new PaymentService($this->app));
    }

    /**
     * 创建订单
     * @param array $data
     * @return bool
     * @throws BusinessException
     */
    public function createOrder(array $data): bool
    {
        // 验证必要参数
        if (empty($data['user_id']) || empty($data['product_id']) || empty($data['quantity'])) {
            throw new BusinessException('参数错误');
        }

        return $this->transaction(function() use ($data) {
            // 获取用户信息
            $userRepo = $this->getRepository(self::REPOSITORY_USER);
            $user = $userRepo->detail($data['user_id']);
            if (empty($user)) {
                throw new BusinessException('用户不存在');
            }

            // 获取商品信息
            $productRepo = $this->getRepository(self::REPOSITORY_PRODUCT);
            $product = $productRepo->detail($data['product_id']);
            if (empty($product)) {
                throw new BusinessException('商品不存在');
            }

            // 检查库存
            if ($product['stock'] < $data['quantity']) {
                throw new BusinessException('商品库存不足');
            }

            // 扣减库存
            if (!$productRepo->decreaseStock($data['product_id'], $data['quantity'])) {
                throw new BusinessException('库存扣减失败');
            }

            // 创建订单
            $orderData = [
                'user_id' => $data['user_id'],
                'product_id' => $data['product_id'],
                'quantity' => $data['quantity'],
                'amount' => $product['price'] * $data['quantity'],
                'status' => 1, // 待支付
                'created_at' => date('Y-m-d H:i:s'),
            ];
            
            return $this->repository->create($orderData);
        });
    }

    /**
     * 支付订单
     * @param int $orderId
     * @return bool
     * @throws BusinessException
     */
    public function payOrder(int $orderId): bool
    {
        if ($orderId <= 0) {
            throw new BusinessException('订单ID无效');
        }

        return $this->transaction(function() use ($orderId) {
            // 获取订单信息
            $order = $this->repository->detail($orderId);
            if (empty($order)) {
                throw new BusinessException('订单不存在');
            }

            if ($order['status'] !== 1) {
                throw new BusinessException('订单状态异常');
            }

            // 创建支付记录
            /** @var PaymentService $paymentService */
            $paymentService = $this->getService(self::SERVICE_PAYMENT);
            $payment = $paymentService->create([
                'user_id' => $order['user_id'],
                'order_id' => $orderId,
                'amount' => $order['amount'],
                'payment_method' => 'balance'
            ]);

            // 执行支付
            if (!$paymentService->pay($payment['id'])) {
                throw new BusinessException('支付失败');
            }

            // 更新订单状态
            return $this->repository->update($orderId, [
                'status' => 2, // 已支付
                'paid_at' => date('Y-m-d H:i:s')
            ]);
        });
    }

    /**
     * 取消订单
     * @param int $orderId
     * @return bool
     * @throws BusinessException
     */
    public function cancelOrder(int $orderId): bool
    {
        if ($orderId <= 0) {
            throw new BusinessException('订单ID无效');
        }

        return $this->transaction(function() use ($orderId) {
            // 获取订单信息
            $order = $this->repository->detail($orderId);
            if (empty($order)) {
                throw new BusinessException('订单不存在');
            }

            if ($order['status'] !== 1) {
                throw new BusinessException('订单状态异常');
            }

            // 如果存在支付记录,需要退款
            /** @var PaymentService $paymentService */
            $paymentService = $this->getService(self::SERVICE_PAYMENT);
            $payment = $this->repository->getPaymentByOrderId($orderId);
            if ($payment && $payment['status'] === PaymentService::STATUS_SUCCESS) {
                if (!$paymentService->refund($payment['id'])) {
                    throw new BusinessException('退款失败');
                }
            }

            // 恢复库存
            $productRepo = $this->getRepository(self::REPOSITORY_PRODUCT);
            if (!$productRepo->increaseStock($order['product_id'], $order['quantity'])) {
                throw new BusinessException('库存恢复失败');
            }

            // 更新订单状态
            return $this->repository->update($orderId, [
                'status' => 0, // 已取消
                'cancel_at' => date('Y-m-d H:i:s')
            ]);
        });
    }
} 